<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @current-change="handleCurrentChange"  :page-size="pageSize" :total="total" v-on:click="getDictionarys">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="dictionarys" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" >
			</el-table-column>
			<el-table-column prop="sn" label="标识" sortable>
			</el-table-column>
			<el-table-column prop="name" label="名称"  sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"  :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog destroy-on-close :title="title" :visible.sync="dictionaryFormVisible" :close-on-click-modal="false">
			<el-form :model="dictionaryForm" label-width="80px" :rules="dictionaryFormRules" ref="dictionaryForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="dictionaryForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="标识" prop="sn">
					<el-input v-model="dictionaryForm.sn" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="dictionaryFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="dictionaryLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
                details:[],
				total: 0,
				page: 1,
                pageSize:5,
				listLoading: false,
				sels: [],//列表选中列

				dictionaryFormVisible: false,//编辑界面是否显示
				dictionaryLoading: false,
				dictionaryFormRules: {
					email: [
						{ required: true, message: '请输入邮箱', trigger: 'blur' }
					],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ],
                    username: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
				},
                title:"",
				//编辑界面数据
				dictionaryForm: {
                    id:null,
                    name:'',
					sn:'',
                    dictionarys:{}
				},

                // 关联属性处理
                dictionarys: []

			}
		},
		methods: {
            search() {
                //查询完，原来分页条件已经没用了，要跑到第一页去
                this.page = 1;
                this.getDictionarys();
                this.getDetails();
            },

			handleCurrentChange(val) {
				this.page = val;
				this.getDictionarys();
                this.getDetails();
			},

			//获取员工列表
			getDictionarys() {
				let para = {
					currentPage: this.page,
					pageSize:this.pageSize,
					keyword: this.filters.keyword
				};
				this.listLoading=true;
			  this.$http.post("/dictionary",para)
                  .then(result=>{
                      result=result.data;
                      this.total=result.totals;
                      this.dictionarys=result.rows;
                      this.listLoading=false;
                  })
                  .catch(result=>{
                      alert("系统错误！")
                  })
			},

            //获取员工列表
            getDetails() {
                let para = {
                    currentPage: this.page,
                    pageSize:this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading=true;
                this.$http.post("/detail",para)
                    .then(result=>{
                        result=result.data;
                        this.total=result.totals;
                        this.details=result.rows;
                        this.listLoading=false;
                    })
                    .catch(result=>{
                        alert("系统错误！")
                    })
            },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					/*let para = { id: row.id };
					removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});*/
                    //    由于后端的删除接口使根据resultful风格来编码的，所以我们这里要给他弄成相对应的风格
                    let url = "/dictionary/"+row.id;
                    this.$http.delete(url)
                        .then(result=> {
                                result=result.data;//{sucess:false,message}
                                //去除忙等框
                                this.listLoading = false;

                                if (result.success) {
                                    //删除成功我们跳回第一页，防止有那一页还没数据继续停留的bug
                                    this.page=1;
                                    //提示
                                    this.$message({
                                        message: '删除成功',
                                        type: 'success'
                                    });
                                    //重新查找数据
                                    this.getDictionarys();
                                    this.getDetails();
                                }else {
                                    //提示
                                    this.$message({
                                        message: result.message,
                                        type: 'error'
                                    });
                                    //重新查找数据
                                    this.getDictionarys();
                                    this.getDetails();
                                }
                            }
                        )
                        .catch(result=>{
                            //去除忙等框
                            this.listLoading = false;
                            //提示
                            this.$message({
                                message: '系统错误',
                                type: 'error'
                            });
                        })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                this.title="编辑";
                this.dictionaryFormVisible = true;
				this.dictionaryForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
			    this.title="新增";
				this.dictionaryForm = {//清空
                    /*<id property="id" column="id"></id>
                    <result property="username" column="username"></result>
                    <result property="email" column="email"></result>
                    <result property="phone" column="phone"></result>
                    <result property="state" column="state"></result>
                    <result property="age" column="age"></result>*/
					id:null,
                    name: '',
                    sn:'',
                    dictionarys:[]
				};
                this.dictionaryFormVisible = true; //显示新增框
			},
			//保存
			save: function () {
				this.$refs.dictionaryForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.dictionaryLoading = true;
							/*//NProgress.start();
							let para = Object.assign({}, this.dictionaryForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editUser(para).then((res) => {
								this.dictionaryLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['dictionaryForm'].resetFields();
								this.dictionaryFormVisible = false;
								this.getUsers();
							});*/

						//	我们为了在下面做添加和修改，因为我们之前将数据双向绑定，所以我们对数据操作之前我们先拷贝一份数据
                            let para = Object.assign({}, this.dictionaryForm);
                            //我们发闪送请求到后台，直接保存数据
                            this.$http.put("/dictionary",para)
                                .then(result=>{
                                    result=result.data;
                                    if (result.success){
                                        //成功就去除忙等狂
                                        this.dictionaryLoading = false;
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        //重新获取数据
                                        this.getDictionarys();
                                    }else {
                                        //失败就去除忙等狂
                                        this.dictionaryLoading = false;
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                        //重新获取数据
                                        this.getDictionarys();
                                    }
                                    this.dictionaryFormVisible = false;
                                })
                                .catch(result=>{
                                    this.dictionaryLoading = false;
                                    this.dictionaryFormVisible = false;
                                    alert("系统错误")
                                })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},

			//合并两张表
            arraySpanMethod({ row, column, rowIndex, columnIndex }) {
                if (rowIndex % 2 === 0) {
                    if (columnIndex === 0) {
                        return [1, 2];
                    } else if (columnIndex === 1) {
                        return [0, 0];
                    }
                }
            },

			//合并两张表
            objectSpanMethod({ row, column, rowIndex, columnIndex }) {
                if (columnIndex === 0) {
                    if (rowIndex % 2 === 0) {
                        return {
                            rowspan: 2,
                            colspan: 1
                        };
                    } else {
                        return {
                            rowspan: 0,
                            colspan: 0
                        };
                    }
                }
            },
            //批量删除
            batchRemove: function () {
                //我们不需要toString，因为我们直接返回一个数组给后台进行遍历一个个删除
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    // let para = { ids: ids };
                    /* batchRemoveDepartment(para).then((res) => {
                         this.listLoading = false;
                         //NProgress.done();
                         this.$message({
                             message: '删除成功',
                             type: 'success'
                         });
                         this.getDictionarys();
                     });*/
                    //传递数组参数到后台批量删除，不需要let para = { ids: ids };
                    this.$http.patch("/dictionary",ids)
                        .then(result=>{
                            result = result.data;
                            //去除忙等框
                            this.listLoading = false;
                            if (result){
                                //成功提示
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page =1; //删除后跳转第一页
                                //从新获取数据
                                this.getDictionarys();
                            }else {
                                //去除忙等框
                                this.listLoading = false;
                                //失败提示
                                this.$message({
                                    message: '删除成功'+ result.message,
                                    type: 'error'
                                });
                                //从新获取数据
                                this.getDictionarys();
                            }
                        })
                        .catch(result=>{
                            alert("系统错误");
                            this.getDictionarys();
                            this.listLoading = false;
                        })

                }).catch(() => {

                });
            }
        },
		mounted() {
			this.getDictionarys();
			this.getDetails();
		}
	}

</script>

<style scoped>
</style>